﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HHL_Acc.HHL_BussAcc.DataObject;
using HHL_Acc.HHL_EntityAcc;
using HHL_Acc.HHL_Util;
using HHL_Util;

namespace HHL_Acc
{
    public partial class PhieuNhapKhoFRM : Form
    {
        private int count;
        private int statusForm = 1; // default

        public PhieuNhapKhoFRM()
        {
            InitializeComponent();
            InitDanhSachPhieuNhap();
            InitThongTinChiTiet();
            // this.MdiParent = MDI_FRM;
        }

        #region "Thong Tin Chi Tiet"

        private void InitThongTinChiTiet()
        {
            //GenLogins currLogin = SessionUser.GenLogin

            txtReceiveDetailInfo.Text = AppInfo.GenLogin.Name;

            int currYear = DateTime.Now.Year;
            int pos = currYear - 5;
            while (pos < currYear + 5)
            {
                cbYearDetailInfo.Items.Add(pos);

                pos++;
            }
            cbYearDetailInfo.SelectedIndex = 5;

            // load data 
            var sysImpMethodBus = new SysImpMethodBus();
            cbImportTypeDetailIinfo.DataSource = sysImpMethodBus.GetSysImpMethodList();

            // create column for gvDetailTicketDetailInfo
            var columnItemsList = new List<ColumnItem>();
            columnItemsList.Add(new ColumnItem("Idx", "STT", CommonConstant.SEQ_WIDTH));
            columnItemsList.Add(new ColumnItem("Price", "Giá vé", CommonConstant.PRICE_WIDTH));
            columnItemsList.Add(new ColumnItem("Amount", "Số lượng", CommonConstant.AMOUNT_TICKET_WIDTH));
            columnItemsList.Add(new ColumnItem("SerialStart", "Số Serial BD", CommonConstant.SERIAL_WIDTH));
            columnItemsList.Add(new ColumnItem("SerialEnd", "Số Serial KT", CommonConstant.SERIAL_WIDTH));
            columnItemsList.Add(new ColumnItem("ImpId", "ImpId", CommonConstant.SERIAL_WIDTH));
            CommonGuiUtil.CreateColumns(ref gvDetailTicketDetailInfo, columnItemsList);

            gvDetailTicketDetailInfo.RowsRemoved += gviewThongTinVe_RowsRemoved;

            gvDetailTicketDetailInfo.Columns["ImpId"].Visible = false;
        }

        private void btnThemThongTinVe_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtSerailStartDetailInfo.Text))
            {
                MessageBox.Show("Vui lòng nhập số serail bắt đầu");
                return;
            }
            if (txtAmountDetailInfo.Value == 0)
            {
                MessageBox.Show("Vui lòng nhập số số lượng vé nhập ");
                return;
            }

            // check exist
            int rowsCount = gvDetailTicketDetailInfo.Rows.Count;
            if (rowsCount > 0)
            {
                String serailFrom = string.Empty;
                for (int i = 0; i < rowsCount; i++)
                {
                    serailFrom = (String)gvDetailTicketDetailInfo.Rows[i].Cells["SerialStart"].Value;
                    if (serailFrom != null)
                    {
                        if (serailFrom.EndsWith(txtSerailStartDetailInfo.Text.ToUpper()))
                        {
                            // exist in gridview
                            return;
                        }
                    }
                }
            }

            if (rowsCount > 0)
            {
                count++;
            }
            //  String donGia = CommonUtil.ConvertCurrencyToString((long)txtTabTTCTDonGiaVe.Value);
            //   String donGia = common
            gvDetailTicketDetailInfo.Rows.Add(new Object[]
                                                  {
                                                      count,
                                                      "00",
                                                     (int) txtAmountDetailInfo.Value, // case to int
                                                      txtSerailStartDetailInfo.Text,
                                                      txtSerialEndDetailInfo.Text
                                                  });
        }


        private void gviewThongTinVe_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            removeRowInGridViewThongTinVe();
        }

        private void btnDeleteDetailTab_Click(object sender, EventArgs e)
        {
            if (gvDetailTicketDetailInfo.SelectedRows[0] != null)
            {
                gvDetailTicketDetailInfo.Rows.Remove(gvDetailTicketDetailInfo.SelectedRows[0]);
                removeRowInGridViewThongTinVe();
            }


        }

        private void removeRowInGridViewThongTinVe()
        {
            if (gvDetailTicketDetailInfo.Rows.Count > 0)
            {
                DialogResult result = MessageBox.Show("Bạn có muốn xóa những thông tin này không?", "Thông báo",
                                                      MessageBoxButtons.YesNo);
                //gviewThongTinVe.SelectedRows
                if (result == DialogResult.Yes)
                {
                    count = gvDetailTicketDetailInfo.Rows.Count;
                    for (int i = 0; i < count - 1; i++)
                    {
                        gvDetailTicketDetailInfo.Rows[i].Cells["Idx"].Value = (i + 1);
                    }
                }
            }
        }

        #endregion

        #region "Danh Sach Phieu Nhap"

        public void InitDanhSachPhieuNhap()
        {
            var columnItemsList = new List<ColumnItem>();
            columnItemsList.Add(new ColumnItem("Idx", "STT", CommonConstant.SEQ_WIDTH));
            columnItemsList.Add(new ColumnItem("ImpNumber", "Số phiếu", CommonConstant.IMPORT_NUMBER_WIDTH));
            columnItemsList.Add(new ColumnItem("IssueYear", "Năm", CommonConstant.YEAR_WIDTH));
            columnItemsList.Add(new ColumnItem("ImpDate", "Ngày nhập", CommonConstant.DATE_WIDTH));
            columnItemsList.Add(new ColumnItem("ImpMethodNameUnicode", "Loại nhập", CommonConstant.DATE_WIDTH));
            columnItemsList.Add(new ColumnItem("Qty", "Số lượng", CommonConstant.AMOUNT_TICKET_WIDTH));
            columnItemsList.Add(new ColumnItem("Receiver", "Người giao", CommonConstant.RECEIVER_WIDTH));
            columnItemsList.Add(new ColumnItem("ImpNameUnicode", "Người nhận", CommonConstant.IMPORT_NAME_WIDTH));
            columnItemsList.Add(new ColumnItem("NotesUnicode", "Ghi chú", CommonConstant.NOTES_WIDTH));

            CommonGuiUtil.CreateColumns(ref gvImportListTicket, columnItemsList);

            var smiImportsBus = new SmiImportsBus();
            gvImportListTicket.DataSource = smiImportsBus.GetListSmiImportL();

            dtTabDSPNNgayNhapFrom.Value = new DateTime(CommonConstant.TICK_DATE_MIN);

            int currYear = DateTime.Now.Year;
            int pos = currYear - 5;
            while (pos < currYear + 5)
            {
                cboxTabDSPNYear.Items.Add(pos);

                pos++;
            }
            cboxTabDSPNYear.SelectedIndex = 5;
        }

        private void btnTabDSPNSearch_Click(object sender, EventArgs e)
        {
            var smiImportsBus = new SmiImportsBus();
            int? imNumber = null;
            int? year = null;
            if (txtTabDSPNPhieuNhap.Text.TrimEnd() != String.Empty)
            {
                imNumber = int.Parse(txtTabDSPNPhieuNhap.Text);
            }
            if (cboxTabDSPNYear.SelectedText.TrimEnd() != String.Empty)
            {
                year = int.Parse(cboxTabDSPNYear.SelectedText);
            }

            //gvTabDSPNNhapKho.DataSource = smiImportsBus.GetListSmiImport(imNumber, year,
            //     dtTabDSPNNgayNhapFrom.Value, dtTabDSPNNgayNhapTo.Value);
        }


        private void button5_Click(object sender, EventArgs e)
        {
        }

        #endregion

        private void txtTabTTCTSoLoc_ValueChanged(object sender, EventArgs e)
        {
        }

        private void txtSerailStartDetailInfo_Validated(object sender, EventArgs e)
        {
            txtSerailStartDetailInfo.Text = txtSerailStartDetailInfo.Text.ToUpper();
            if (txtSerialEndDetailInfo.Text.TrimEnd() == String.Empty)
            {
                String serialStart = txtSerailStartDetailInfo.Text;
                if (CommonBusUtil.IsSerial(txtSerailStartDetailInfo.Text))
                {
                    try
                    {
                        long serial = long.Parse(serialStart.Substring(8));
                        serial += CommonConstant.DEFAULT_TICKET_IMPORT - 1;
                        txtSerialEndDetailInfo.Text = serialStart.Substring(0, 8) + serial;
                    }
                    catch
                    {
                        CommonUtil.WriteToLogFile("Nhap Serial khong dung: " + serialStart);
                    }
                }
            }
        }


        private void ChangeStatusDetail()
        {
            switch (statusForm)
            {
                case 1: // default
                    btnInsert.Text = "Thêm mới";
                    btnEdit.Text = "Chỉnh sửa";
                    btnDel.Text = "Xóa";
                   // btnConfirmDetailInfo.Text = "In";
                    txtTicketNoDetaitInfo.Enabled = false;
                    txtSerialEndDetailInfo.Enabled = false;
                    txtTicketNoDetaitInfo.Enabled = false;
                    btnDel.Visible = true;
                   // btnConfirmDetailInfo.Visible = true;

                    // init
                    InitThongTinChiTiet();
                    loadDetailInfo();
                    break;
                case 2: // insert 
                    btnInsert.Text = "Bỏ qua";
                    btnEdit.Text = "Lưu";

                    txtTicketNoDetaitInfo.Text = "";
                    txtTicketNoDetaitInfo.Enabled = true;

                    txtSerailStartDetailInfo.Text = "";
                    txtSerialEndDetailInfo.Enabled = true;

                    txtSerialEndDetailInfo.Text = "";
                    txtTicketNoDetaitInfo.Enabled = true;
                    txtReceiveDetailInfo.Text = AppInfo.GenLogin.Name;
                    txtNoteDetailInfo.Text = "";
                    txtNoteDetailInfo.Enabled = true;
                    cbImportTypeDetailIinfo.SelectedIndex = 0;

                    gvDetailTicketDetailInfo.Rows.Clear();
                    btnDel.Visible = false;
                   // btnConfirmDetailInfo.Visible = false;

                    btnEdit.Enabled = true;
                   // btnConfirmDetailInfo.Enabled = true;
                    break;
                case 3: // update
                    btnInsert.Text = "Bỏ qua";
                    btnEdit.Text = "Lưu";

                    txtTicketNoDetaitInfo.Enabled = true;
                    txtSerialEndDetailInfo.Enabled = true;
                    txtTicketNoDetaitInfo.Enabled = true;

                    txtReceiveDetailInfo.Text = AppInfo.GenLogin.Name;

                    txtNoteDetailInfo.Enabled = true;
                    btnDel.Visible = false;
                    btnConfirmDetailInfo.Visible = false;
                    break;

            }
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            switch (statusForm)
            {
                case 1: // change status to insert
                    statusForm = 2;
                    break;
                case 2: // bỏ qua insert
                case 3: // bỏ qua update
                    statusForm = 1;
                    break;

            }
            ChangeStatusDetail();
        }

        private void InsertForm()
        {
            // SmiImport Information
            SmiImports smiImports = new SmiImports();
            smiImports.ImpId = CommonUtil.MakeStringID();
            smiImports.ImpNumber = int.Parse(txtTicketNoDetaitInfo.Text);
            smiImports.Deliver = txtDeliverDetailInfo.Text;
            smiImports.Importer = AppInfo.GenLogin.Login;
            smiImports.NotesVni = txtNoteDetailInfo.Text;

            SysImpMethod sysImpMethod = (SysImpMethod)cbImportTypeDetailIinfo.SelectedItem;
            smiImports.ImpMethod = sysImpMethod.ImpMethod;
            smiImports.ImpDate = DateTime.Now.Date;
            smiImports.LastModified = DateTime.Now;
            smiImports.ImpHour = DateTime.Now.Hour;
            smiImports.IssueYear = DateTime.Now.Year;
            smiImports.Login = AppInfo.GenLogin.Login;
            smiImports.ShiftId = 0;
            smiImports.Status = 0;

            // SmiImport information
            List<SmiImportDetails> smiImportDetailList = new List<SmiImportDetails>();
            int rowsCount = gvDetailTicketDetailInfo.Rows.Count;
            SmiImportDetails smiImportDetail = null;
            for (int i = 0; i < rowsCount; i++)
            {
                smiImportDetail = new SmiImportDetails();
                smiImportDetail.ImpID = smiImports.ImpId;
                if (gvDetailTicketDetailInfo.Rows[i].Cells["SerialStart"].Value == null)
                {
                    break;
                }
                smiImportDetail.SerialFrom = (String)gvDetailTicketDetailInfo.Rows[i].Cells["SerialStart"].Value;
                smiImportDetail.Price = int.Parse((String)gvDetailTicketDetailInfo.Rows[i].Cells["Price"].Value);
                smiImportDetail.TicketCode = CommonBusUtil.GetSerialTicketCode(smiImportDetail.SerialFrom).ToString();
                smiImportDetail.Status = 0;
                if (gvDetailTicketDetailInfo.Rows[i].Cells["Amount"] != null)
                {
                    smiImportDetail.Quality = (int)gvDetailTicketDetailInfo.Rows[i].Cells["Amount"].Value;

                }


                smiImportDetailList.Add(smiImportDetail);

            }

            SmiImportsBus smiImportsBus = new SmiImportsBus();
            int rslt = smiImportsBus.InsertSmiImport(smiImports, smiImportDetailList);
            if (rslt == 1)
            {
                MessageBox.Show("Thêm mới vé thành công");
            }
            else
            {
                MessageBox.Show("Đã có lỗi xảy ra. Vui lòng kiểm tra lại hệ thống");
            }
        }

        private void UpdateForm()
        {
            // throw new NotImplementedException();
            // SmiImport Information
            if (gvImportListTicket.SelectedRows.Count > 0 && gvImportListTicket.SelectedRows[0] != null)
            {
                SmiImports smiImports = (SmiImports)gvImportListTicket.SelectedRows[0].DataBoundItem;
                //smiImports.ImpId = CommonUtil.MakeStringID();
                smiImports.ImpNumber = int.Parse(txtTicketNoDetaitInfo.Text);
                smiImports.Deliver = txtDeliverDetailInfo.Text;
                smiImports.Importer = AppInfo.GenLogin.Login;
                smiImports.NotesVni = txtNoteDetailInfo.Text;

                SysImpMethod sysImpMethod = (SysImpMethod)cbImportTypeDetailIinfo.SelectedItem;
                smiImports.ImpMethod = sysImpMethod.ImpMethod;
                // smiImports.ImpDate = DateTime.Now;
                smiImports.LastModified = DateTime.Now;
                // smiImports.ImpHour = DateTime.Now.Hour;
                smiImports.IssueYear = DateTime.Now.Year;
                smiImports.Login = AppInfo.GenLogin.Login;
                smiImports.ShiftId = 0;
                smiImports.Status = 0;

                // SmiImport information
                List<SmiImportDetails> smiImportDetailList = new List<SmiImportDetails>();
                int rowsCount = gvDetailTicketDetailInfo.Rows.Count;
                SmiImportDetails smiImportDetail = null;
                for (int i = 0; i < rowsCount; i++)
                {
                    smiImportDetail = new SmiImportDetails();
                    smiImportDetail.ImpID = smiImports.ImpId;
                    if (gvDetailTicketDetailInfo.Rows[i].Cells["SerialStart"].Value == null)
                    {
                        break;
                    }
                    smiImportDetail.SerialFrom = (String)gvDetailTicketDetailInfo.Rows[i].Cells["SerialStart"].Value;
                    //smiImportDetail.Price = int.Parse((String) gvDetailTicketDetailInfo.Rows[i].Cells["Price"].Value);
                    smiImportDetail.TicketCode =
                        CommonBusUtil.GetSerialTicketCode(smiImportDetail.SerialFrom).ToString();
                    smiImportDetail.Status = 0;
                    if (gvDetailTicketDetailInfo.Rows[i].Cells["Amount"] != null)
                    {
                        smiImportDetail.Quality = (int)gvDetailTicketDetailInfo.Rows[i].Cells["Amount"].Value;
                    }
                    smiImportDetailList.Add(smiImportDetail);
                }
                SmiImportsBus smiImportsBus = new SmiImportsBus();
                int rslt = smiImportsBus.UpdateSmiImport(smiImports, smiImportDetailList);
                if (rslt == 1)
                {
                    MessageBox.Show("Cập nhật vé thành công");
                }
                else
                {
                    MessageBox.Show("Đã có lỗi xảy ra. Vui lòng kiểm tra lại hệ thống");
                }
            }
        }


        private void txtSerailStartDetailInfo_TextChanged(object sender, EventArgs e)
        {
            bool isSerial = CommonBusUtil.IsSerial(txtSerailStartDetailInfo.Text);
            if (isSerial)
            {
                txtAmountDetailInfo.Value = 100;
                String serialEnd = txtSerailStartDetailInfo.Text.Substring(0, 9);
                serialEnd += String.Format("{0:000000}", 100);
                txtSerialEndDetailInfo.Text = serialEnd;
            }
            // txtSerailStartDetailInfo.Text = txtSerailStartDetailInfo.Text.ToUpper();
            //    txtSerailStartDetailInfo.s
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                loadDetailInfo();
            }
        }

        private void loadDetailInfo()
        {
            if (gvImportListTicket.SelectedRows.Count > 0 && gvImportListTicket.SelectedRows[0] != null)
            {
                SmiImports smiImport = (SmiImports)gvImportListTicket.SelectedRows[0].DataBoundItem;

                txtTicketNoDetaitInfo.Text = smiImport.ImpNumber == null ? "" : smiImport.ImpNumber + "";
                txtReceiveDetailInfo.Text = smiImport.ImpNameUnicode;
                txtNoteDetailInfo.Text = smiImport.NotesUnicode;

                // load ticket list detail
                SmiImportDetailBus smiImportDetailBus = new SmiImportDetailBus();
                List<SmiImportDetails> importDetailsList =
                    smiImportDetailBus.GetListImportDetailByImpId(smiImport.ImpId);
                gvDetailTicketDetailInfo.Rows.Clear();
                if (importDetailsList != null)
                {
                    String serialTo = string.Empty;

                    foreach (SmiImportDetails importDetail in importDetailsList)
                    {
                        serialTo = CommonBusUtil.GenerateSerialEnd(importDetail.SerialFrom, importDetail.Quality);
                        gvDetailTicketDetailInfo.Rows.Add(new Object[]
                                                              {
                                                                  importDetail.Idx,
                                                                  importDetail.Price,
                                                                  importDetail.Quality,
                                                                  importDetail.SerialFrom,
                                                                  serialTo
                                                              });
                    }
                }

                // check status
                btnEdit.Enabled = true;
                if (smiImport.Status == 1)
                {
                    btnEdit.Enabled = false;
                    btnConfirmDetailInfo.Enabled = false;
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            switch (statusForm)
            {
                case 1:// default - click update first time
                    statusForm = 3;
                    break;
                case 2: // insert
                    statusForm = 2;
                    InsertForm();
                    return;
                case 3: // update
                    UpdateForm();
                    statusForm = 1;
                    break;

            }
            ChangeStatusDetail();
        }

        private void gvDetailTicketDetailInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (gvDetailTicketDetailInfo.SelectedRows[0] != null)
            {
                //SmiImportDetails smiImportDetails =  gvDetailTicketDetailInfo.SelectedRows[0].
                object dataBoundItem = gvDetailTicketDetailInfo.SelectedRows[0].DataBoundItem;
                txtSerailStartDetailInfo.Text = (String)gvDetailTicketDetailInfo.SelectedRows[0].Cells["SerialStart"].Value;
                txtSerialEndDetailInfo.Text = (String)gvDetailTicketDetailInfo.SelectedRows[0].Cells["SerialEnd"].Value;
                //txtSerialEndDetailInfo.Text = (String)gvDetailTicketDetailInfo.SelectedRows[0].Cells["SerialTo"].Value;
                if (gvDetailTicketDetailInfo.SelectedRows[0].Cells["Amount"].Value != null)
                {
                    txtAmountDetailInfo.Value = (int)gvDetailTicketDetailInfo.SelectedRows[0].Cells["Amount"].Value;
                }
            }
        }
    }
}
